<template>
  <div class="page">
    <div class="page-container">
			<Header activeId="4" />
			<div class="content">
        <Bread :data="[{text: '首页', href: '/'}, {text: '景区地图'}]" />
        <div id="map" style="height: 80vh;"></div>
        <span v-b-toggle.sidebar-1 class="setting">
          <client-only><b-icon icon="gear-fill"></b-icon></client-only>
        </span>
			</div>
      <Footer />
		</div>
    <b-sidebar v-model="isShowSidebar" id="sidebar-1" title="地图标识" shadow>
      <div class="form-checkbox-group">
        <b-form-checkbox-group
          id="checkbox-group-1"
          v-model="selected"
          :options="options"
          name="flavour-1"
        ></b-form-checkbox-group>
      </div>
    </b-sidebar>
	</div>
</template>

<script>
import Header from '../components/header.vue'
import Footer from '../components/footer.vue'
import Bread from '../components/bread.vue'

export default {
	components: {
    Header,
    Footer,
    Bread,
	},

  data: function(){
    return {
      opened: true,
      typeOptions: [
        {label: 'WMTS', value: 'wmts'},
        {label: 'WMS', value: 'wms'},
        {label: 'UT', value: 'ut'}
      ],
      layerUrl: '',
      layerType: 'wms',
      layers: [],
	    map: null,
      selected: [],
      options: [],
      signs: [],
      markers: [],
      layers: [],
      isShowSidebar: false
    }
  },

  watch: {
    selected () {
      this.renderSign()
    }
  },

  mounted() {
    this.initMap()
    this.initControl()
  },

  methods: {
    initMap() {
      const map = this.$L.map('map', {
        attributionControl: false
      }).setView([29.7525, 103.5457], 16)
      this.map = map
      // 使用高德的WMS服务
      var layer = this.$L.tileLayer('http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}&key=3fdbc36a0d5cce94e69f8156afaf6f6c', {
        subdomains: ['1', '2', '3', '4'],
        minZoom: 1, // 最小放缩级别
        maxZoom: 19 // 最大放缩级别
      })
      map.addLayer(layer)

      // 渲染标记
      this.loadMakers()
      // 加载区块
      this.loadPolygons()
    },
    // 初始化设置
    initControl () {
      let me = this
      let map = this.map
      L.EditControl = L.Control.extend({
        options: {
          position: 'topleft',
          callback: null,
          kind: '',
          html: `<span>
            <svg viewBox="0 0 16 16" width="1em" height="1em" focusable="false" role="img" aria-label="gear fill" xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="bi-gear-fill b-icon bi"><g><path d="M9.405 1.05c-.413-1.4-2.397-1.4-2.81 0l-.1.34a1.464 1.464 0 0 1-2.105.872l-.31-.17c-1.283-.698-2.686.705-1.987 1.987l.169.311c.446.82.023 1.841-.872 2.105l-.34.1c-1.4.413-1.4 2.397 0 2.81l.34.1a1.464 1.464 0 0 1 .872 2.105l-.17.31c-.698 1.283.705 2.686 1.987 1.987l.311-.169a1.464 1.464 0 0 1 2.105.872l.1.34c.413 1.4 2.397 1.4 2.81 0l.1-.34a1.464 1.464 0 0 1 2.105-.872l.31.17c1.283.698 2.686-.705 1.987-1.987l-.169-.311a1.464 1.464 0 0 1 .872-2.105l.34-.1c1.4-.413 1.4-2.397 0-2.81l-.34-.1a1.464 1.464 0 0 1-.872-2.105l.17-.31c.698-1.283-.705-2.686-1.987-1.987l-.311.169a1.464 1.464 0 0 1-2.105-.872l-.1-.34zM8 10.93a2.929 2.929 0 1 1 0-5.86 2.929 2.929 0 0 1 0 5.858z"></path></g></svg>
          </span>`
        },
        onAdd: function(map) {
          var container = L.DomUtil.create('div', 'leaflet-control leaflet-bar'),
            link = L.DomUtil.create('a', '', container)
          link.href = '#'
          link.title = '点击设置地图'
          link.innerHTML = this.options.html
          L.DomEvent.on(link, 'click', () => {
            me.isShowSidebar = !me.isShowSidebar
          }, this)
          return container
        }
      })
      map.addControl(new L.EditControl())
    },
    loadMakers () {
      this.queryMarkerData().then(res => {
        let types = res[0].value || []
        let selected = []
        this.options = types.map(item => {
          selected.push(item.id)
          return {
            text: item.name,
            value: item.id
          }
        })
        this.selected = selected
        let markers = res[1].value || []
        this.signs = markers.map(item => {
          return {
            type: item.typeId,
            lng: parseFloat(item.longitude),
            lat: parseFloat(item.latitude),
            title: item.name,
            icon: types.find(node => node.id === item.typeId)?.icon
          }
        })
      }).finally(() => {
        this.renderSign()
      })
    },
    // 查询标记数据
    queryMarkerData () {
      let defer1 = this.$service.map.queryType({}, {$http: this.$axios}).then(res => {
        let data = res.data
        let rows = data?.rows || []
        return rows
      })
      let defer2 = this.$service.map.queryMarker({}, {$http: this.$axios}).then(res => {
        let data = res.data
        let rows = data?.rows || []
        return rows
      })

      return Promise.allSettled([defer1, defer2])
    },
    // 渲染标记
    renderSign () {
      this.clearSign()
      let selected = this.selected
      let signs = this.signs.filter(item => {
        return selected.find(node => String(node) === String(item.type))
      })
      this.markers = signs.map(item => {
        let marker = this.$L.marker([item.lat, item.lng], {
          title: item.title || undefined,
          icon: L.icon({
            iconUrl: item.icon || '/assets/images/mark_b.png',
            iconSize: [15, 24],
            iconAnchor: [8, 24],
          })
        })
        marker.addTo(this.map)
        marker.bindPopup(item.title)
        return marker
      })
    },
    // 清除标记
    clearSign () {
      this.markers.forEach((marker) => {
        this.map.removeLayer(marker)
      })
      this.markers = []
    },
    loadPolygons () {
      this.queryPolygonData().then(list => {
        this.renderPolygon(list)
      })
    },
    // 查询区块数据
    queryPolygonData () {
      return this.$service.map.queryPolygon({}, {$http: this.$axios}).then(res => {
        let data = res.data
        let rows = data?.rows || []
        return rows
      })
    },
    // 渲染区块
    renderPolygon (list) {
      list.forEach(item => {
        let data = item.geodata
        try {
          data = JSON.parse(data)
        } catch (e) {
          data = []
        }
        data = data.map(item => {
          return item.reverse()
        })
        let map = this.map
        let layer = L.polygon([
          data || []
        ], {color: item.color || '#3388ff', weight: 2}).addTo(map)
        layer.bindPopup(item.name)
        this.layers.push(layer)
      })
    },
    // 清除图层
    clearLayers () {
      this.layers.forEach((layer) => {
        this.map.removeLayer(layer)
      })
    }
	}
}
</script>

<style lang="less">
.content {
  position: relative;
  overflow: hidden;
  z-index: 3;
  .setting {
    display: none;
    position: absolute;
    top: 64px;
    right: 10px;
    z-index: 9999;
    font-size: 20px;
    color: #666;
    cursor: pointer;
    &:hover {
      color: #007bff;
    }
  }
}
.form-checkbox-group {
  padding: 0 20px;
  .custom-control-inline {
    width: 100px;
  }
}
</style>